/**
 * Copyright (C) 2008 Wideplay Interactive.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.neodatis.warp;

import org.neodatis.odb.ODB;
import org.neodatis.odb.ODBFactory;
import org.neodatis.odb.ODBServer;

import com.wideplay.warp.persist.InternalWorkManager;
import com.wideplay.warp.persist.ManagedContext;

/**
 * Internal WorkManager.
 * @author Robbie Vanbrabant
 */
public class NeodatisInternalWorkManager implements InternalWorkManager<ODB> {
    private final ODBServerProvider odbServerProvider;

    public NeodatisInternalWorkManager(ODBServerProvider objectServerProvider) {
        this.odbServerProvider = objectServerProvider;
    }
    
    public ODB beginWork() {
    	ODBServer odbServer = this.odbServerProvider.get();
        NeodatisSettings settings = this.odbServerProvider.getSettings();
        ODB odb;
        if (!ManagedContext.hasBind(ODB.class, odbServer)) {
            //open local server client
            if (settings.isLocal()) {
            	// TODO no user/password here, like Db4O?
            	odb = odbServer.openClient("base1");
            	
            //open remote client
            } else if (settings.isRemote()) {
            	// TODO configure db name + user + password
            	odb = ODBFactory.openClient(settings.getHost(), settings.getPort(), "base1");

            //open file based client
            } else {
            	odb = ODBFactory.open(settings.getDatabaseFileName());
            }
            ManagedContext.bind(ODB.class, odbServer, odb);
        } else {
            odb = ManagedContext.getBind(ODB.class, odbServer);
        }
        // TODO isClosed() doesn't exist
        if (odb != null) {
            return odb;
        } else {
            // this one has been closed, try again
            ManagedContext.unbind(ODB.class, odbServer);
            return beginWork();
        }
    }

    public void endWork() {
    	ODBServer os = this.odbServerProvider.get();
        if (ManagedContext.hasBind(ODB.class, os)) {
        	ODB objectContainer = ManagedContext.unbind(ODB.class, os);
        	// TODO  && !objectContainer.ext().isClosed() - isClosed() not implemented in Neodatis
            if (objectContainer != null) objectContainer.close();
        }
    }
}
